package com.xhl.common.CglibProxy;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * 代理模式之 cglib 动态代理
 * @Author CazCen
 * @Date 2021/12/2 11:58
 */
public class ServiceCglibProxy implements MethodInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(ServiceCglibProxy.class);

    /**
     * 目标对象
     */
    private Object target;

    public ServiceCglibProxy(Object target) {
        this.target = target;
    }

    /**
     * 给目标对象创建代理对象
     */
    public Object getProxyInstance(){
        //工具类
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(target.getClass());
        //设置回调函数
        enhancer.setCallback(this);
        //创建子类代理对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        logger.info("前面进行增强.....");
        Object obj = method.invoke(target);
        logger.info("后面进行增强.....");
        return obj;
    }
}
